package com.sinodata.bsm.cicp.collector;

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.util.DBConnectionUtil;
import com.sun.rowset.CachedRowSetImpl;

/**
 * 
 * <p>
 * Description: 
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-5-18 上午9:51:23    liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public abstract class AbstractJDBCCollector extends Collector {

    protected static final Logger logger = Logger.getLogger(AbstractJDBCCollector.class);

    /**
     * 返回离线封装的数据集 如果需要对数据进行缓存，则调用此方法
     *
     * @param dbtype
     * @param ip
     * @param serverName
     * @param sql
     * @return
     * @throws Exception
     */
    protected ResultSet getCachedResultSet(String dbtype, String ip, String serverName, String sql) throws Exception {
        Connection conn = null;
        //String cachedKey = ip + "/" + serverName + "/" + sql;
        //   ResultSet resultSet = (ResultSet) ValueBuffer.getInstance().get(cachedKey, (int) super.interval);
        //        if (resultSet != null) {
        //            resultSet.first();
        //            return resultSet;
        //        }

        Statement statement = null;
        ResultSet result = null;
        try {
            conn = DBConnectionUtil.getInstance().getConnection(dbtype, ip, serverName);
            if (dbtype.equals("sybase")) {
                // 此处serverName读取catalog值
                conn.setCatalog(serverName);
            }
            logger.info("[SQL]" + sql.trim());
            statement = conn.createStatement();
            result = statement.executeQuery(sql.trim());
            CachedRowSetImpl cachedRowSet = new CachedRowSetImpl();
            cachedRowSet.populate((ResultSet) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { ResultSet.class }, new ResultSetProxy(result)));
            //            ValueBuffer.getInstance().put(cachedKey, cachedRowSet);
            return cachedRowSet;
        } catch (Exception e) {
            logger.error("failed to collect by jdbc", e);
            throw e;
        } finally {
            if (result != null) {
                try {
                    result.close();
                } catch (Exception e2) {
                }
                result = null;
            }

            if (statement != null) {
                try {
                    statement.close();
                } catch (Exception e2) {
                }
                statement = null;
            }

            DBConnectionUtil.getInstance().returnConnection(conn);
        }
    }
}
